<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import { NModal, NCard, NSpace, NButton, NInputNumber, NSpin } from 'naive-ui';
import { fetchLineageGraph, type LineageGraph } from '@/service/api/dataplatform/metadata';

const visible = ref(false);
const loading = ref(false);
const tableId = ref<number>(0);
const depth = ref(2);
const graphData = ref<LineageGraph | null>(null);
const graphContainer = ref<HTMLElement>();

// 打开弹窗
async function open(id: number) {
  tableId.value = id;
  visible.value = true;
  await loadGraphData();
}

// 加载血缘图数据
async function loadGraphData() {
  loading.value = true;
  try {
    const { data } = await fetchLineageGraph(tableId.value, depth.value);
    graphData.value = data;
    
    await nextTick();
    renderGraph();
  } catch (error) {
    console.error('加载血缘图失败:', error);
  } finally {
    loading.value = false;
  }
}

// 渲染血缘图
function renderGraph() {
  if (!graphContainer.value || !graphData.value) return;
  
  // 清空容器
  graphContainer.value.innerHTML = '';
  
  // 简化版渲染 - 使用 SVG 绘制
  const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  svg.setAttribute('width', '100%');
  svg.setAttribute('height', '600');
  svg.style.border = '1px solid #e0e0e0';
  svg.style.borderRadius = '4px';
  
  const nodes = graphData.value.nodes || [];
  const edges = graphData.value.edges || [];
  
  // 计算节点位置 (简单的层次布局)
  const nodePositions = new Map<number, { x: number; y: number }>();
  const layers = new Map<number, number[]>();
  
  // 简单分层
  nodes.forEach((node, index) => {
    const layer = Math.floor(index / 3);
    if (!layers.has(layer)) {
      layers.set(layer, []);
    }
    layers.get(layer)!.push(node.id);
  });
  
  // 计算位置
  const layerHeight = 150;
  const nodeWidth = 120;
  const startX = 100;
  const startY = 50;
  
  layers.forEach((nodeIds, layer) => {
    const layerWidth = nodeIds.length * (nodeWidth + 50);
    nodeIds.forEach((nodeId, index) => {
      const x = startX + index * (nodeWidth + 50);
      const y = startY + layer * layerHeight;
      nodePositions.set(nodeId, { x, y });
    });
  });
  
  // 绘制边
  edges.forEach(edge => {
    const sourcePos = nodePositions.get(edge.source);
    const targetPos = nodePositions.get(edge.target);
    
    if (sourcePos && targetPos) {
      const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
      line.setAttribute('x1', String(sourcePos.x + 60));
      line.setAttribute('y1', String(sourcePos.y + 20));
      line.setAttribute('x2', String(targetPos.x + 60));
      line.setAttribute('y2', String(targetPos.y + 20));
      line.setAttribute('stroke', '#1890ff');
      line.setAttribute('stroke-width', '2');
      line.setAttribute('marker-end', 'url(#arrowhead)');
      svg.appendChild(line);
      
      // 添加标签
      const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
      text.setAttribute('x', String((sourcePos.x + targetPos.x) / 2 + 60));
      text.setAttribute('y', String((sourcePos.y + targetPos.y) / 2 + 15));
      text.setAttribute('fill', '#666');
      text.setAttribute('font-size', '12');
      text.textContent = edge.label;
      svg.appendChild(text);
    }
  });
  
  // 绘制节点
  nodes.forEach(node => {
    const pos = nodePositions.get(node.id);
    if (!pos) return;
    
    // 节点矩形
    const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
    rect.setAttribute('x', String(pos.x));
    rect.setAttribute('y', String(pos.y));
    rect.setAttribute('width', '120');
    rect.setAttribute('height', '40');
    rect.setAttribute('fill', node.type === 'TABLE' ? '#e6f7ff' : '#fff7e6');
    rect.setAttribute('stroke', node.type === 'TABLE' ? '#1890ff' : '#fa8c16');
    rect.setAttribute('stroke-width', '2');
    rect.setAttribute('rx', '4');
    svg.appendChild(rect);
    
    // 节点文本
    const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
    text.setAttribute('x', String(pos.x + 60));
    text.setAttribute('y', String(pos.y + 25));
    text.setAttribute('text-anchor', 'middle');
    text.setAttribute('fill', '#333');
    text.setAttribute('font-size', '14');
    text.textContent = node.label;
    svg.appendChild(text);
  });
  
  // 添加箭头标记
  const defs = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
  const marker = document.createElementNS('http://www.w3.org/2000/svg', 'marker');
  marker.setAttribute('id', 'arrowhead');
  marker.setAttribute('markerWidth', '10');
  marker.setAttribute('markerHeight', '10');
  marker.setAttribute('refX', '9');
  marker.setAttribute('refY', '3');
  marker.setAttribute('orient', 'auto');
  
  const polygon = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
  polygon.setAttribute('points', '0 0, 10 3, 0 6');
  polygon.setAttribute('fill', '#1890ff');
  marker.appendChild(polygon);
  defs.appendChild(marker);
  svg.insertBefore(defs, svg.firstChild);
  
  graphContainer.value.appendChild(svg);
}

// 刷新图表
function handleRefresh() {
  loadGraphData();
}

// 关闭弹窗
function close() {
  visible.value = false;
  graphData.value = null;
}

defineExpose({ open, close });
</script>

<template>
  <NModal
    v-model:show="visible"
    preset="card"
    title="数据血缘关系图"
    :style="{ width: '90%', maxWidth: '1200px' }"
    :segmented="{ content: true }"
  >
    <NSpace vertical :size="16">
      <!-- 控制栏 -->
      <NSpace align="center">
        <span>深度:</span>
        <NInputNumber v-model:value="depth" :min="1" :max="5" :step="1" style="width: 120px" />
        <NButton type="primary" @click="handleRefresh">
          <icon-ic-round-refresh class="mr-4px text-16px" />
          刷新
        </NButton>
        <NButton @click="close">关闭</NButton>
      </NSpace>

      <!-- 图表容器 -->
      <div v-if="loading" class="flex justify-center items-center h-600px">
        <NSpin size="large" />
      </div>
      <div v-else ref="graphContainer" class="w-full min-h-600px"></div>

      <!-- 说明 -->
      <NCard size="small" title="图例">
        <NSpace>
          <div class="flex items-center">
            <div class="w-16px h-16px bg-blue-100 border-2 border-blue-500 rounded mr-8px"></div>
            <span>表</span>
          </div>
          <div class="flex items-center">
            <div class="w-16px h-16px bg-orange-100 border-2 border-orange-500 rounded mr-8px"></div>
            <span>视图</span>
          </div>
          <div class="flex items-center">
            <div class="w-40px h-2px bg-blue-500 mr-8px"></div>
            <span>数据流向</span>
          </div>
        </NSpace>
      </NCard>
    </NSpace>
  </NModal>
</template>

<style scoped>
/* 添加必要的样式 */
</style>
